package com.obrempon.credit.market.ui.activity

import android.annotation.SuppressLint
import android.os.CountDownTimer
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.View
import com.obrempon.credit.market.R
import com.obrempon.credit.market.common.CommonActivity
import com.obrempon.credit.market.databinding.ObremponCreditReviewingActBinding
import com.obrempon.credit.market.event.ObremponEventData
import com.obrempon.credit.market.event.ObremponEventPointType
import com.obrempon.credit.market.utils.helper.ObremponCreditStatusHelper
import com.obrempon.credit.market.utils.helper.ObremponProcessHelper

/**
 * ObremponCredit
 * @Author wwdeng
 * @CreateTime: 2024/12/16 13:41
 * @Annotation：额度审核中
 */
class ObremponCreditReviewingAct: CommonActivity() {
    lateinit var binding: ObremponCreditReviewingActBinding
    private var countdownTimer: MyCountDownTimer? = null
    //等待时长
    private var countdown = 10

    override fun takeObremponRootView(): View {
        binding = ObremponCreditReviewingActBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initObremponView() {
        setObremponTitleBarVisibility(View.VISIBLE)
        setObremponTextTitleVisibility(View.GONE)
        setObremponBackBtnVisibility(View.INVISIBLE)
        setObremponRightBtnRes(R.mipmap.obrempon_customer_icon)
        rootViewBinding.rootLayout.setBackgroundColor(getColor(R.color.color_ff0569ff))

        val showTipsKey = getString(R.string.obrempon_credit_reviewing_leave_again)
        val showTipsText = String.format(getString(R.string.obrempon_credit_reviewing_approved_times),showTipsKey)
        val startTipsIndex = showTipsText.indexOf(showTipsKey)
        val tipsSpannable = SpannableString(showTipsText)
        tipsSpannable.setSpan(ForegroundColorSpan(getColor(R.color.color_ff0569ff)), startTipsIndex, startTipsIndex + showTipsKey.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.textApprovedTimesTips.text = tipsSpannable
    }

    override fun initObremponListener() {
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog("Credit Reviewing Page")
            addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_CUSTOMER,"Credit Reviewing Page")
        }
    }

    override fun takeObremponData() {
        takeObremponCreditStatusAction()
    }

    /**
     * 额度审核中
     */
    @SuppressLint("SetTextI18n")
    fun showObremponCreditLimitReviewingViews() {
        //启动倒计时
        startObremponCreditLimitCountdownTimer()
    }

    /**
     * 额度审核成功
     */
    private fun showObremponCreditLimitSuccessViews() {
        if (countdownTimer != null){
            countdownTimer?.cancel()
        }
        finish()
    }

    /**
     * 额度审核失败
     */
    private fun showObremponCreditLimitFailedViews() {
        onIntent(ObremponCreditRejectedAct::class.java)
        if (countdownTimer != null){
            countdownTimer?.cancel()
        }
        finish()
    }

    /**
     * 开启倒计时
     */
    private fun startObremponCreditLimitCountdownTimer(){
        countdown = 10
        if (countdownTimer == null){
            countdownTimer = MyCountDownTimer(this,countdown.toLong() * 1000,1000)
        }
        countdownTimer?.start()
    }

    /**
     * 显示状态
     */
    private fun showObremponCreditLimitCountdownText(){
        binding.textCountdown.text = "$countdown"
    }

    private fun showObremponCreditLimitCountdownComplete(){
        publishEventData(ObremponEventData(ObremponEventData.TYPE.OBREMPON_PROCESS_REFRESH))
    }

    class MyCountDownTimer(private val act: ObremponCreditReviewingAct, millisInFuture: Long, countDownInterval: Long): CountDownTimer(millisInFuture, countDownInterval) {
        override fun onTick(millisUntilFinished: Long) {
            // 这里每隔一段时间（定时器间隔）会被调用
            // 可以在这里更新UI，显示剩余时间
            act.countdown = (millisUntilFinished / 1000).toInt()
            act.showObremponCreditLimitCountdownText()
        }
        override fun onFinish() {
            // 倒计时完成时被调用
            act.showObremponCreditLimitCountdownComplete()
        }
    }

    override fun onObremponPublishEvent(event: ObremponEventData) {
        super.onObremponPublishEvent(event)
        if (event.eventType == ObremponEventData.TYPE.OBREMPON_PROCESS_REFRESHED){
            takeObremponCreditStatusAction()
        }
    }

    /**
     * 获取授信状态
     */
    private fun takeObremponCreditStatusAction(){
        hideObremponLoading()
        val isCreditReviewing = ObremponCreditStatusHelper.ObremponCreditStatusRepository().isCreditReviewing()
        //授信中
        if (isCreditReviewing){
            showObremponCreditLimitReviewingViews()
            return
        }

        val creditStatus = ObremponProcessHelper.takeObremponAuthBeforeRiskStatus()
        val isCreditRejected = ObremponCreditStatusHelper.ObremponCreditStatusRepository().isCreditRejected(creditStatus)
        //授信被拒绝
        if (isCreditRejected){
            showObremponCreditLimitFailedViews()
            return
        }
        //授信完成
        showObremponCreditLimitSuccessViews()
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(ObremponEventPointType.PAGE.OBREMPON_PAGE_CREDIT_REVIEWING_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(ObremponEventPointType.PAGE.OBREMPON_PAGE_CREDIT_REVIEWING_END)
        if (countdownTimer != null){
            countdownTimer?.cancel()
            countdownTimer = null
        }
    }
}